import random

from django.shortcuts import render, reverse, HttpResponse, redirect
from django.views import View

from article.models import Article
from libs.CommonResponse import CommonReponse
from user.forms import RegisterForm
from user.models import UserInfo
from django.contrib import auth
from django.contrib.auth.decorators import login_required


# Create your views here.

def register(request, *args, **kwargs):
    register_form = RegisterForm()
    if request.method == "POST" and request.is_ajax():
        # 获取 POST 请求携带的所有键值对数据
        data = request.POST
        # 将 POST 请求携带的数据扔给 form组件校验
        register_form = RegisterForm(data)
        if not register_form.is_valid():
            return CommonReponse(code=2001, errors=register_form.errors)
        # 获取所有校验通过后的数据
        clean_data = register_form.cleaned_data
        # 删除 confirm_password 字段
        clean_data.pop("confirm_password")
        # 获取头像的文件数据
        avatar_data = request.FILES.get("avatar")
        # 将文件数据添加到 校验通过后的数据中
        clean_data["avatar"] = avatar_data

        # 调用用户模型表创建用户
        user_obj = UserInfo.objects.create_user(**clean_data)

        return CommonReponse(code=2000, message=f"当前用户 {user_obj.username} 注册成功!", next_url=reverse("login"))
    return render(request, "register.html", locals())


# 登录
class LoginView(View):
    def get(self, request, *args, **kwargs):
        return render(request, "login.html", locals())

    def post(self, request, *args, **kwargs):
        if request.is_ajax():
            data = request.POST
            # print(data)
            # 因为没有走Form组件
            username = data.get("username")
            password = data.get("password")
            confirm_password = data.get("confirm_password")
            valid_code = data.get("verify")
            if not all([username, password, confirm_password, valid_code]):
                return CommonReponse(code=2001, errors=f"请补齐参数")
            # 判断username是否存在
            if not UserInfo.objects.filter(username=username).exists():
                return CommonReponse(code=2002, errors=f"当前用户 {username} 不存在!")
            if not password or not confirm_password or password != confirm_password:
                return CommonReponse(code=2003, errors=f"当前两次密码输入不一致!")
            # 校验验证码
            # 获取原来的验证码
            # 这里的参数要注意是img的src地址
            valid_code_true = request.session.get('valid_code_str')
            print(valid_code_true)
            if valid_code.upper() != valid_code_true.upper():
                return CommonReponse(code=2004, errors=f"验证码输入错误!")
            # 校验密码和注册时的密码是否一致
            user_obj = auth.authenticate(username=username, password=confirm_password)
            if not user_obj:
                return CommonReponse(code=2005, errors=f"用户名或密码错误!")
            # 保存用户登录状态
            auth.login(request, user_obj)
            return CommonReponse(code=2000, message=f'当前用户{username}登录成功!', next_url=reverse('home'))


def get_validCode(request):
    from libs.validCode import get_validCode_img
    data = get_validCode_img(request)
    return HttpResponse(data)


# 注销登录
@login_required
def logout(request, *args, **kwargs):
    # 通过auth 模块的注销登陆
    auth.logout(request)
    return reverse('login')


@login_required
def change_password(request, *args, **kwargs):
    if request.method == "POST" and request.is_ajax():
        data = request.POST
        username = data.get('username')
        old_password = data.get('old_password')
        print(old_password)
        new_password = data.get('new_password')
        print(new_password)
        confirm_password = data.get('confirm_password')
        # 校验
        is_password = request.user.check_password(old_password)
        if not all(['old_passowrd', 'new_password', 'confirm_password']):
            return CommonReponse(code=2002, errors="请补齐参数！")
        if new_password != confirm_password:
            return CommonReponse(code=2003, errors="两次密码不一致！")
        if not is_password:
            return CommonReponse(code=2001, errors="当前密码错误！")
        # 修改密码操作
        request.user.set_password(confirm_password)
        request.user.save()
        # 注销原来用户再修改
        auth.logout(request)
        return CommonReponse(code=2000, errors="当前用户密码修改成功！", next_url=reverse('login'))
